// 授权中间件
import jwt from "jsonwebtoken";
import process from "../config/config.default.js";
import { UNAUTHORIZATION, TOKEN_EXPIRED } from "../constant/err.type.js";
const { JWT_SECRET } = process.env;

export async function auth(ctx, next) {
  try {
    const authorization = ctx.headers.authorization;

    if (!authorization) {
      console.error("没有token");
      return ctx.app.emit("error", UNAUTHORIZATION, ctx);
    }
    const token = authorization.replace("Bearer ", "");

    const user = jwt.verify(token, JWT_SECRET);

    ctx.state.user = user;
    await next();
  } catch (error) {
    switch (error.name) {
      case "TokenExpiredError":
        // token 过期
        console.error("token 过期");
        return ctx.app.emit("error", TOKEN_EXPIRED, ctx);
      case "JsonWebTokenError":
        // token 错误
        console.error("token 错误");
        return ctx.app.emit("error", UNAUTHORIZATION, ctx);
      default:
        return ctx.app.emit("error", UNAUTHORIZATION, ctx);
    }
  }
}
// 判断是否管理员
export async function isAdmin(ctx, next) {
  const { isAdmin } = ctx.state.user;
  if (!isAdmin) {
    console.error("没有管理员权限");
    return ctx.app.emit(
      "error",
      {
        code: 10001,
        message: "没有管理员权限",
        result: "",
      },
      ctx
    );
  }
  await next();
}
